package com.jmb.waimao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jmb.waimao.entity.EmailAddress;
import com.jmb.waimao.service.EmailAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Controller for email address management
 */
@RestController
@RequestMapping("/api/email-addresses")
@Slf4j
public class EmailAddressController {

    @Autowired
    private EmailAddressService emailAddressService;

    /**
     * Import email addresses from CSV file
     * 
     * @param file CSV file containing email addresses
     * @param groupName Group name for the imported emails
     * @return Import result
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importEmails(
            @RequestParam("file") MultipartFile file,
            @RequestParam("groupName") String groupName) {
        
        log.info("Importing emails for group: {}", groupName);
        
        try {
            int count = emailAddressService.importFromCsv(file, groupName);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Successfully imported " + count + " email addresses");
            result.put("count", count);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error importing emails", e);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Failed to import email addresses: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * Get email addresses by group
     * 
     * @param groupName Group name
     * @return List of email addresses
     */
    @GetMapping("/group/{groupName}")
    public ResponseEntity<List<EmailAddress>> getByGroup(@PathVariable String groupName) {
        List<EmailAddress> emails = emailAddressService.getByGroup(groupName);
        return ResponseEntity.ok(emails);
    }

    /**
     * Get all email addresses with pagination
     * 
     * @param page Page number
     * @param size Page size
     * @return Paged list of email addresses
     */
    @GetMapping
    public ResponseEntity<Page<EmailAddress>> getAll(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Page<EmailAddress> pageRequest = new Page<>(page, size);
        LambdaQueryWrapper<EmailAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmailAddress::getDeleted, 0)
                    .orderByDesc(EmailAddress::getCreateTime);
        
        Page<EmailAddress> result = emailAddressService.page(pageRequest, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * Add a single email address
     * 
     * @param emailAddress Email address to add
     * @return Added email address
     */
    @PostMapping
    public ResponseEntity<EmailAddress> add(@RequestBody EmailAddress emailAddress) {
        emailAddress.setCreateTime(LocalDateTime.now());
        emailAddress.setUpdateTime(LocalDateTime.now());
        emailAddress.setDeleted(0);
        
        emailAddressService.save(emailAddress);
        return ResponseEntity.ok(emailAddress);
    }

    /**
     * Update an email address
     * 
     * @param id Email address ID
     * @param emailAddress Email address to update
     * @return Updated email address
     */
    @PutMapping("/{id}")
    public ResponseEntity<EmailAddress> update(
            @PathVariable Long id,
            @RequestBody EmailAddress emailAddress) {
        
        emailAddress.setId(id);
        emailAddress.setUpdateTime(LocalDateTime.now());
        
        emailAddressService.updateById(emailAddress);
        return ResponseEntity.ok(emailAddress);
    }

    /**
     * Delete an email address
     * 
     * @param id Email address ID
     * @return Success message
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable Long id) {
        EmailAddress emailAddress = emailAddressService.getById(id);
        if (emailAddress != null) {
            emailAddress.setDeleted(1);
            emailAddress.setUpdateTime(LocalDateTime.now());
            emailAddressService.updateById(emailAddress);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Email address deleted successfully");
            
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Email address not found");
            
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * Get all group names
     * 
     * @return List of group names
     */
    @GetMapping("/groups")
    public ResponseEntity<List<String>> getAllGroups() {
        List<String> groups = emailAddressService.list(new LambdaQueryWrapper<EmailAddress>()
                .select(EmailAddress::getGroupName)
                .groupBy(EmailAddress::getGroupName)
                .eq(EmailAddress::getDeleted, 0))
                .stream()
                .map(EmailAddress::getGroupName)
                .distinct()
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(groups);
    }
}
